from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django.views.decorators.http import require_http_methods
from exercise.models import ExerciseInfo
from nurse.models import NurseInfo

# Create nurse views here.


class LoginView(View):

    def get(self, request):
        """用户get请求渲染登陆页面"""
        return render(request, 'nurse/login.html')

    def post(self, request):
        """用户post请求验证用户身份"""
        try:
            name = request.POST.get('name')
            password = request.POST.get('password')
            maintain_entry = request.POST.get('maintain_entry')
            user = NurseInfo.objects.filter(name=name)[0]
            if user:
                encrypt_pwd = user.password
                if check_password(password, encrypt_pwd):
                    response = JsonResponse({'code': 1})  # 成功
                    if maintain_entry:
                        response.set_cookie("user_status", "is_login", max_age=10*24*60*60)
                    else:
                        response.set_cookie("user_status", "is_login")
                    # 将登陆用户的ID和姓名存入session
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name

                    return response
                else:
                    return JsonResponse({'code': 0})  # 密码错误
            else:
                return JsonResponse({'code': 0})     # 用户不存在
        except Exception as e:
            print(e)
            return JsonResponse({'code': 0})


class RegisterView(View):

    def get(self, request):
        """用户get请求渲染注册页面"""
        return render(request, 'nurse/register.html')

    def post(self, request):
        """用户post请求创建账号"""
        try:
            # 获取来自register.html模板的表单数据
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            password = request.POST.get('password')
            print('新用户 = ', name, phone, password)
            encrypt_pwd = make_password(password)
            # 创建一个新用户
            NurseInfo.objects.create(name=name, phone=phone, password=encrypt_pwd)
            return JsonResponse({'code': 1})  # 注册成功
        except Exception as e:
            print(e)
            return JsonResponse({'code': 0})  # 注册失败


@require_http_methods('POST')
def check_user(request):
    """验证是否存在同名用户"""
    name = request.POST.get('name')
    user = NurseInfo.objects.filter(name=name)
    print('user', user)
    if user:
        return JsonResponse({'code': 0})
    else:
        return JsonResponse({'code': 1})


def home(request):
    """用户的主页面"""
    # 获得做题数量最多的两个人
    two_nurse = NurseInfo.objects.all().order_by('-total_count')[:2]
    # 获得总习题数
    exercise_count = ExerciseInfo.objects.count()
    # 等到当前登陆的用户信息
    user_name = request.session.get('user_name', '游客')
    nurse = NurseInfo.objects.get(name=user_name)
    # 获取当前用户的刷题数
    total_count = nurse.total_count
    # 统计当前用户的正确率
    correct_count = nurse.correct_count
    if total_count:
        correct_rate = correct_count / total_count * 100
    # 获取题库并统计不同分类的题目数量，用列表方式返回
    category = [0, 0, 0, 0, 0, 0]
    category[0] = ExerciseInfo.objects.filter(category='基础护理学').count()
    category[1] = ExerciseInfo.objects.filter(category='内科护理学').count()
    category[2] = ExerciseInfo.objects.filter(category='外科护理学').count()
    category[3] = ExerciseInfo.objects.filter(category='妇产科护理学').count()
    category[4] = ExerciseInfo.objects.filter(category='儿科护理学').count()
    category[5] = ExerciseInfo.objects.filter(category='医学伦理学').count()

    return render(request, 'index.html', locals())


def profile(request):
    """用户个人中心"""
    pk = request.session.get('user_id')
    nurse = NurseInfo.objects.get(id=pk)

    return render(request, 'nurse/profile.html', {'nurse': nurse})


@require_http_methods('GET')
def nurse_logout(request):
    """用户退出登陆"""
    response = redirect('nurse:login')
    response.delete_cookie('user_status')

    return response

